package com.astro.app;

import java.io.File;
import java.util.Date;
import java.util.Scanner;

import org.apache.log4j.Logger;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.astro.business.UserManager;
import com.astro.common.util.EncryptionHelper;
import com.astro.domain.bean.TblUser;

public class LoadData {
	
	static final Logger log = Logger.getLogger(LoadData.class);
	
	public static void main(String[] args) {
		System.out.println("Program is starting...");
		try {
			// Initial application context
			System.out.println(" spring context is loading...");
			AppContext.setSpringContext(new ClassPathXmlApplicationContext(
					"spring-datasource-config.xml"));
			System.out.println(" spring context is loaded!");

			UserManager userManager = (UserManager) AppContext
					.getSpringContext().getBean("userManager");
			
			AppConfig appConfig = (AppConfig) AppContext.getSpringContext().getBean(AppConfig.class);
			
			try {

				Scanner scanner = new Scanner(new File(appConfig.getCSVPath()));
				
				scanner.useDelimiter(",");

				scanner.nextLine();
				TblUser tblUser = null;
				int count = 1;
				while (scanner.hasNextLine()) {
					System.out.println("Start Processing line: " + count);
					String[] nextLine = scanner.nextLine().split(",");

					String email 		= nextLine[0].trim();
					String groupCode 	= nextLine[1].trim();
					System.out.println("	email 	  = " + email);
					System.out.println("	groupCode = " + groupCode);
					
					// get user by email
					tblUser = userManager.getUserByEmail(email);
					
					if(tblUser == null || tblUser.getUserId() == null) {
						// Insert User
						tblUser = new TblUser();
						
						tblUser.setEmail(email);
						tblUser.setGroupCode(groupCode);
						// MD5 password
						tblUser.setPassword(EncryptionHelper.encodeMD5("12345"));
						tblUser.setLocked("N");
						tblUser.setEnabled("Y");
						tblUser.setCreatedBy("backend");
						tblUser.setCreatedDate(new Date());
						tblUser.setUpdatedDate(new Date());
						
						userManager.addUser(tblUser);
					}
					System.out.println("End Processing line: " + count);
					count ++;
				}
				scanner.close();
				
			} catch (Exception e) {
				e.printStackTrace();
			}

			// List Users


		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("Done!");
	}
}
